﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.Forecasts.Update;

public class UpdateForecastsCommandHandler : IRequestHandler<UpdateForecastsCommandRequest, UpdateForecastsCommandResponse>
{
    private readonly IForecastRepository _forecastRepository;
    private readonly IMapper _mapper;

    public UpdateForecastsCommandHandler(IForecastRepository forecastRepository, IMapper mapper)
    {
        _forecastRepository = forecastRepository;
        _mapper = mapper;
    }

    public async Task<UpdateForecastsCommandResponse> Handle(UpdateForecastsCommandRequest request, CancellationToken cancellationToken)
    {
        var forecast = await _forecastRepository.FirstOrDefaultAsync(x => request.ForecastId == x.Id, cancellationToken);
        if (forecast == null) throw new NotFoundException($"Прогноз погоды с id '{request.ForecastId}' не найден");

        forecast.Temperature = request.Temperature;
        forecast.WeatherCondition = request.WeatherCondition;
        forecast.Datetime = request.DateTime.ToUniversalTime();

        await _forecastRepository.UpdateAsync(forecast, cancellationToken);
        return _mapper.Map<UpdateForecastsCommandResponse>(forecast);
    }
}